package com.sky.handler;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;
import java.util.HashMap;

/**
 * @projectName: netty-cloud
 * @package: com.sky.handler
 * @className: MyAccessDeniedHandler
 * @author: zhl
 * @description: 访问未授权资源时处理器
 * @date: 2024/4/25 15:42
 * @version: 1.0
 */
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    /**
     * Handles an access denied failure.
     *
     * @param request               that resulted in an <code>AccessDeniedException</code>
     * @param response              so that the user agent can be advised of the failure
     * @param accessDeniedException that caused the invocation
     * @throws IOException      in the event of an IOException
     * @throws ServletException in the event of a ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        HashMap<String,Object> hashMap = new HashMap<>(16);
        hashMap.put("code",400);
        hashMap.put("msg","你未获得该资源授权");
        hashMap.put("data",accessDeniedException.getMessage());
        String json = JSON.toJSONString(hashMap);

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);
    }
}
